/*-------------
 * pr.js
 * 
 * Main JS module for Payment Ranger
 */

// Globals
var prPage = null;
var prDialog = null;

// Constants
var TL_DOMAINS = 'com net edu gov us tv info biz';
var PR_URL = "/Ranger";
var EMAIL_PTRN = /^.*@.*\..*/;
var SCAN_URL = "zxing://scan/?newtab=no&ret=http%3A%2F%2Fpspygear%2Eappspot%2Ecom%2FRanger%3Faction%3DScan%26vin%3D%7BCODE%7D%26newtab%3Dno";
var MSG_BOARD = 'msgBoard';

// Main Page Control
var PRPage = new Class({
    /** set parent */
    Extends: SitePage,
    
    /** constructor */
    initialize: function() {
        this.parent('PaymentRanger');
        
        // check for ui msgs
        if (errMsg)
            this.feedBack(usrMsg,1);
        else
            this.feedBack(usrMsg);
       
        try {    
            if(DID) {
                dlr = $('dealer');
                for(o=0; o< dlr.options.length; o++) 
                    if(dlr.options[o].value == DID)
                        dlr.selectedIndex = o;
            }
        }
        catch(ex) {}
    },
   
    /**
     * set feedback message into the
     * message board if err is a positive
     * value, display in red.
     */
    feedBack: function(msg,err) {
        c = (err == undefined) ? "#000" : '#A00'; 
        $(MSG_BOARD).set("text",msg);
        $(MSG_BOARD).setStyle("color",c);
    },

    /**
     * Go home
     */
    home: function(chunk) {
        var data = "action=Home";
        
        if (chunk) {
            data = "$1&chunk=1".$$(data);
        }
        new Request.HTML({
           url: PR_URL,
           update: 'main_content'
        }).post(data);
    },

    /**
     * Clear session info...
     */
    clearSession: function() {
    	window.location.href='/Ranger?action=Clear';
    },
    
    /**
     * Go home
     */
    buyIt: function() {
        form = $('usrInput')
        pymts = form.pymts.value;
        params = "action=Buy&vin=$1&pin=$2&descr=$3&did=$4&pymts=$5".$$(form.vin.value,form.pin.value,form.descr.value,form.did.value,pymts)
        $$log("~~ Buy Request: ($1) ".$$(params));
        $$log("~~ pymts: $1".$$(pymts));
        
        new Request.JSON({
           url: PR_URL,
           method: "post",
           data: params,
           
           onSuccess: function(json,txt) {
               $$log("Buyit: $1".$$(txt));
               alert("A message has been sent to the the dealer. You should expect a call soon.");
           },
           
           onError: function(txt,err) {
               $$log(err);
               $$log(txt);
               alert(txt);
           }
           
        }).send();
    },

    //----------------------
    //    Operations
    //----------------------   
    
    /**
     * Send vin number for pricing
     */ 
    process: function(form) {
        // scrape form for values
        vin = form.vin.value; 
        pin = form.pin.value;
        
        // get selected dealer       
        dlr = form.dealer
        did = dlr.options[dlr.selectedIndex].value
        
        // validations
        if('na' == did)
            alert("Please Select Dealer");            
        else if((vin.length < 5) || (pin.length < 1))
            alert("Please supply values both for VIN and PIN fields");
        else {
            // Houston, we are go    
            $$log("~~ VIN: $1; PIN: $2 ; DID: %s".$$(vin,pin,did));
        
            // send service call    
            new Request.HTML({
               url: PR_URL,
               method: "post",
               data: "action=Process&vin=$1&pin=$2&did=$3".$$(vin,pin,did),
               update: 'main_content'
            }).send();
        }
        
        // all done
        return 0;        
    },
    
    /**
     * Scan VIN # using mobile camera
     * and ZXing scanner
     */   
    scanVIN: function() {
        frm = $('usrInput');
        did = frm.dealer.value;
        pin = frm.pin.value || 0;
        aid = frm.aid.value || 0;
        dat = '%26aid%3D$1%26did%3D$2%26pin%3D$3%26full%3D0'.$$(aid,did,pin);
        surl = "$1$2".$$(SCAN_URL,dat);
        
        $$log("Scan URL: $1".$$(surl));
        
        window.location.href=SCAN_URL;       
    },
        
    //-----------------------
    //  Account Management
    //-----------------------

    /** 
     * Log in user
     */
    authorize: function(form) {
        // gather input
        var uid = form.uid.value;
        var pwd = form.pwd.value;
        var msg = null;
        var rv = true;
                
        $$log("~~ uid: $1".$$(uid));
            
        try {
            // test input requirements
            if( !EMAIL_PTRN.test(uid) )
                msg = "Invalid Email Address!";
            else if(pwd.length < 1) 
                msg = "Password  Required!";
            
            // cancel on error    
            if(msg) {
                alert(msg);
                rv = false;
            }
        }
        catch(exc) {
            // unlikely but....
            $$log("!! Error: $1".$$(exc)); 
            rv = false;
        }
        
        // should we stay or should we go...
        $$log("Submit: $1".$$(rv));
        
        form.submit();
        return false;
    },
    
    /**
     * Create a new account
     */
    createAcct: function(form) {
      // scrape form
      var ema = form.email.value;
      var pwd = form.pwd.value;
      var vp =  form.vpwd.value;
      var nm = form.name.value;
      
      var err = !this.checkEmail(ema) ? "Please enter valid email account" :
                (!nm || nm == "") ? "Name is a Required Field" :
                vp != pwd ? "Password and Verify Password are different" : vp.pwdFormatCheck();
        
      // error somewhere
      if (err) {
          this.feedBack(err,1);
          return false;
      }
      
      // good stuff
      return true;
    },
    
    /** 
     * Enter new password string
     */
    resetPWD: function(form){
        var pwd = form.pwd.value;
        var vp = form.vpwd.value;
        var aid = form.aid.value;
        
        // format check
        var err = vp != pwd ? "Password and Verify Password are different" : vp.pwdFormatCheck();
        
        // err report
        if (err) {
            alert(err);
        }
        else {
            
            // all good
            new Request.HTML({
               url: PR_URL,
               method: "post",
               data: "action=access.Reset&pwd=$1&aid=$2&chunk=1".$$(pwd,aid),
               update: 'main_content',
                              
               onSuccess: function(jsn,txt) {
                   $$log("~~ Reset results: $1".$$(txt));
                   
                   alert("Password Reset Successful!");
               }
             }).send();
        }
        
        return false;
    },

    /**
     * Validate as valid email addr
     */
    checkEmail: function(ema){
        var good = true;
        
        // test for valid email
        try {
            // split acct from domain
            d1 = ema.split("@");
            
            // check both sides
            if((d1[0].length < 1) || (d1[1].length < 1)) 
                throw "No Acct ID";
                
            // split domain     
            d2 = d1[1].split(".");
            if((d2.length < 2) || (TL_DOMAINS.indexOf(d2[d2.length-1]) < 0)) {
                throw "Invalid Domain";
            }
        }         
        catch(exc) {
            // uh oh, try again...
            $$log(exc);
            good = false;
        }
        
        // all done...
        return good;                
    },
    
    /** 
     * Send reset email
     */
    sendReset: function() {
        // be sure we have a dialog open
        if(prDialog) {
            // assume the best                
            var good = true;

            // get email account
            var ema = $('dlgReset').getChildren("form")[0].getChildren('input').getProperty('value')[0];
            
            // assume good stuff
            var msg = "";
            var errmsg;
            
            // if all good, send it along...
            if(this.checkEmail(ema)) {
                // send ot server
                new Request.JSON({
                    url: PR_URL,
                    data: "action=access.Email&ema=$1".$$(ema),
                    method: 'post',
                    
                    onSuccess: function(json, tree) {
                        prDialog.close();
                        
                        // was email sent?                        
                        if (json.code != 200) {
                            msg = json .message;
                            errmsg = 1;
                        }
                        else
                            prPage.feedBack("Check your mail and follow the instructions");
                    }     
                             
                }).send();
            }
            else
                msg = "Invalid Email Address";
                    
            // be kind to users...
            prPage.feedBack(msg,errmsg);                        
    
        }
    },
    
    /**
     * Send email for reseting 
     */
    getEmail: function() {
      prDialog = new MooDialog();
      
      div = new Element("div",{
           id: "dlgReset",
           style: "vertical-align:middle"
      });
      
      div.innerHTML = $('pwdReset').innerHTML;
      prDialog.setContent(div);
      prDialog.open(); 
    }
});

//-------------------------------------------
//Show time!
window.addEvent('domready', function(){
    // starting small
    prPage = new PRPage();
});
